//
//  AIGirlMessageGiftView.swift
//  AIGirl
//
//  Created by Rae on 2024/1/2.
//

import UIKit
import SwiftEntryKit

class AIGirlMessageGiftView: UIView, AnimationProtocol, AnimationDelegate {

    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: 325.0)
    }
    
    func animationContainerViewStyle() -> AnimationViewStyle {
        .bottom
    }
    
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var diamondImg = c_make_ex(UIImageView.self)
        .image("AIGirl_Home_purpleDiamond").mode(.scaleAspectFill).end()
    private lazy var numberBtn = UIIconButton(style: .trailing(itemSpace: 5.5))
    private lazy var sentButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(14.font_bold).corner(15)
        .text("SEND").end()
    
    var giftData: [AIGirlGiftItemModel]?{
        didSet{
            collectionView.reloadData()
        }
    }
    
    var sendGiftClosure: ((_ model: AIGirlGiftItemModel) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = "#1B1325".toColor
        layer.cornerRadius = 30
        layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        
        subviews{
            collectionView
            diamondImg
            numberBtn
            sentButton
        }
        
        collectionView.leading(0).trailing(0).top(10).height(230)
        diamondImg.leading(20).size(32).bottom(30)
        numberBtn.height(32).leading(80)
        numberBtn.CenterY == diamondImg.CenterY
        sentButton.trailing(20).height(30).width(70)
        sentButton.CenterY == diamondImg.CenterY
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10.0, bottom: 0, right: 10.0)
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: 90.0, height: 110.0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlMessageGiftItem.self, forCellWithReuseIdentifier: AIGirlMessageGiftItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        numberBtn.style { v in
            v.iconSize = CGSize(width: 22, height: 22)
            v.setTitleColor(.white, for: .normal)
            v.setImage("AIGirl_Message_Gift_go".toImage, for: .normal)
            let coin = GlobalTool.userModel?.money ?? 0
            v.setTitle(String(coin), for: .normal)
            v.titleLabel?.font = 20.font_bold
        }
        
        NotificationCenter.default.addObserver(forName: .userBalanceChanged, object: nil, queue: nil) { noti in
            let coin = GlobalTool.userModel?.money ?? 0
            self.numberBtn.setTitle(String(coin), for: .normal)
        }
        sentButton.addTarget(self, action: #selector(clickSentButton), for: .touchUpInside)
        numberBtn.addTarget(self, action: #selector(clickPreButton), for: .touchUpInside)
    }
    
    @objc private func clickSentButton(){
        
        var isSel = false
        var md = AIGirlGiftItemModel()
        giftData?.forEach { model in
            if model.isSel {
                isSel = true
                md = model
            }
        }        
        if !isSel {
            "Please select the gift you want to give!".toast_error
            return
        }else{
            
//            sendGiftClosure?(md)
            if Int(md.price) ?? 0 <= GlobalTool.userModel?.money ?? 0 {
                animation.animation(dismiss: self) { [weak self] in
                    self?.sendGiftClosure?(md)
                }
            }else{
                "Diamonds not enough，please recharge!".toast_error
                self.animation.animation(show: AIGirlMessagePremiumView())
                return
            }
        }        
    }
    
    @objc private func clickPreButton(){
        self.animation.animation(show: AIGirlMessagePremiumView())
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension AIGirlMessageGiftView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return giftData?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlMessageGiftItem.description(), for: indexPath) as? AIGirlMessageGiftItem else { return UICollectionViewCell() }
        item.model = giftData?[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [AIGirlGiftItemModel]()
        giftData?.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        giftData = models
        collectionView.reloadData()
    }
}

class AIGirlMessageGiftItem: UICollectionViewCell {
    
    private var giftImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private var selImageView = c_make_ex(UIImageView.self)
        .image("AIGirl_Message_Gift_sel").mode(.scaleAspectFill).end()
    private var diamondButton = UIIconButton(style: .leading(itemSpace: 2.5))

    var model: AIGirlGiftItemModel? {
        didSet {
            guard let md = model else { return }
            giftImageView.loadImage(url: md.preUrl)
            selImageView.isHidden = !md.isSel
            diamondButton.setTitle(md.price, for: .normal)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = .clear
        
        contentView.subviews {
            giftImageView
            diamondButton
            selImageView
        }
        
        selImageView.top(0).leading(0).trailing(0).height(90)
        diamondButton.leading(0).trailing(0).height(16)
        diamondButton.Top == selImageView.Bottom
        giftImageView.size(70).top(10).centerHorizontally()
        
        diamondButton.style { v in
            v.iconSize = CGSize(width: 16, height: 16)
            v.setTitleColor("#E2D2FC".toColor.alpha(0.8), for: .normal)
            v.setImage("AIGirl_Home_purpleDiamond".toImage, for: .normal)
//            v.setTitle("250", for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.isUserInteractionEnabled = false
            v.contentHorizontalAlignment = .center
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
